package com.bestdata.forward.initconfig;

import com.alibaba.fastjson.JSONObject;
import com.bestdata.forward.api.LZInterfaceApi;
import com.bestdata.forward.cachecenter.CacheCenterFactory;
import com.bestdata.forward.httptool.HttpRequestService;
import com.bestdata.forward.httptool.ReturnCodeCenter;
import com.bestdata.forward.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 初始化配置文件处理中心
 *
 * @author chizy
 * @date 2021年1月15日14:19:50
 * @version 1.0.0
 */
@Service
public class InitConfigService {

    private static final Logger logger = LoggerFactory.getLogger(InitConfigService.class);

    //密匙 秘钥
    @Value("${config.key-secret}")
    private String keyAndSecret;

    //设备配置信息
    @Value("${config.device}")
    private String deviceConfig;

    @PostConstruct
    public void startInit(){

        initDeviceConfig();

        logger.info("SUC::::::::::Configuration file device information analysis completed!");

        //初始化秘钥
        boolean initSecret = this.initSecret();

        if(!initSecret){
            logger.error("initSecret error : bridgeSecretMap.size() = {}", CacheCenterFactory.bridgeSecretMap.size());
            return;
        }

        //初始化全局Token
        boolean globalToken = this.initGlobalToken();

        if(!globalToken){
            logger.error("initGlobalToken error : bridgeSecretMap.size() = {} ===>>> CacheCenterFactory.globalTokenMap.size() = {}", CacheCenterFactory.bridgeSecretMap.size(),CacheCenterFactory.globalTokenMap.size());
            return;
        }

        //初始化桥梁结构ID
        boolean idConfig = getIDConfig();

        if(!idConfig){
            logger.error("initGlobalToken error : globalTokenMap.size() = {} ===>>> CacheCenterFactory.bridgeIDMap.size() = {}", CacheCenterFactory.globalTokenMap.size(),CacheCenterFactory.bridgeIDMap.size());
            return;
        }

        //初始化桥梁旗下传感器配置信息
        getSensorComfig();

        logger.info("SUC::::::::::Forwarding configuration initialization completed!");
    }

    /**
     * 桥梁初始化秘钥
     * @return
     */
    public boolean initSecret(){

        String bridgeCodeName = "";
        String key = "";
        String secret = "";

        //示例：  NH:a&b;YX:c&d
        String[] bridgeSecret = this.keyAndSecret.split(";");

        for (int i = 0; i < bridgeSecret.length; i++) {

            String[] bridge = bridgeSecret[i].split(":");

            //桥梁编码
            bridgeCodeName = bridge[0];

            String[] keySecret = bridge[1].split("&");

            //密匙
            key = keySecret[0];
            //秘钥
            secret = keySecret[1];

            BridgeSecretDTO bridgeSecretDTO = new BridgeSecretDTO();
            bridgeSecretDTO.init(bridgeCodeName, key, secret);
            CacheCenterFactory.bridgeSecretMap.put(bridgeCodeName,bridgeSecretDTO);
        }


        System.out.println(CacheCenterFactory.bridgeSecretMap);
        //校验初始化 是否成功
        if(CacheCenterFactory.bridgeSecretMap.size() > 0){
            return true;
        }
        return false;
    }

    /**
     * 初始化全局token
     * 每个桥梁一个token
     * @return
     */
    public static boolean initGlobalToken(){

        CacheCenterFactory.bridgeSecretMap.forEach((bridgeCodeName, bridgeSecretDTO) ->
            {
                //初始化HTTP请求所需参数
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("apiKey",bridgeSecretDTO.getKey());
                paramMap.put("apiSecret",bridgeSecretDTO.getSecret());

                //发送HTTP请求(因目的是获取token，因此参数 )
                String res = HttpRequestService.doPost(LZInterfaceApi.getTokenUrl, paramMap, null);
                //json数组反序列化
                BaseParamDTO baseParamDTO = JSONObject.parseObject(res, BaseParamDTO.class);

                //判断返回码
                boolean status = ReturnCodeCenter.getReturnCodeStatus(baseParamDTO.getCode(), null,null);

                if(status){
                    //返回请求成功
                    String resItem = baseParamDTO.getItem();
                    String[] resStrArr = resItem.substring(resItem.indexOf("{\"")+2,resItem.lastIndexOf("\"}")).split(":");

                    //截取token字符串
                    if("token\"".equals(resStrArr[0])){
                        CacheCenterFactory.globalTokenMap.put(bridgeCodeName,resStrArr[1].substring(resStrArr[1].indexOf('"')+1));
                    }
                }
            }
        );

        System.out.println("全局token："+CacheCenterFactory.globalTokenMap);

        if(CacheCenterFactory.globalTokenMap.size() != CacheCenterFactory.bridgeSecretMap.size()){
            return false;
        }

        return true;
    }

    /**
     * HTTP 获取每座桥的结构ID
     * @return
     */
    public boolean getIDConfig(){

        CacheCenterFactory.globalTokenMap.forEach((bridgeCodeName, token) -> {

            //初始化HTTP请求所需参数
            Map<String, Object> paramMap = new HashMap<>();
            String res = HttpRequestService.doPost(LZInterfaceApi.getBridgeUrl, paramMap, token);
            //json数组反序列化
            BaseParamDTO baseParamDTO = JSONObject.parseObject(res, BaseParamDTO.class);
            //判断返回码
            boolean status = ReturnCodeCenter.getReturnCodeStatus(baseParamDTO.getCode(), null,null);

            if(status){
                //结构物ID
                String ID = baseParamDTO.getItems().get(0).getId();

                CacheCenterFactory.bridgeIDMap.put(bridgeCodeName,ID);
            }
        });

        if(CacheCenterFactory.bridgeIDMap.size() != CacheCenterFactory.globalTokenMap.size()){
            return false;
        }
        return true;

    }


    /**
     * HTTP 通过结构物ID，获取传感器相关配置
     */
    public void getSensorComfig(){

        CacheCenterFactory.bridgeIDMap.forEach((bridgeCodeName, ID) -> {

            //初始化HTTP请求所需参数
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("structureId",ID);

            //从token缓存中取出当前桥对应token
            String token = CacheCenterFactory.globalTokenMap.get(bridgeCodeName);

            //发送HTTP请求(因目的是获取token，因此参数 )
            String res = HttpRequestService.doPost(LZInterfaceApi.getSensorsUrl, paramMap, token);

            //json数组反序列化
            BaseParamDTO baseParamDTO = JSONObject.parseObject(res, BaseParamDTO.class);

            //判断返回码
            boolean status = ReturnCodeCenter.getReturnCodeStatus(baseParamDTO.getCode(),null,null);

            if(status){

                if(baseParamDTO.getItems().size() > 0){

                    /**
                     * 联智北斗平台传感器配置
                     * key：sensorName传感器名称(PMS对应设备名称)
                     * value:SensorConfigDTO传感器配置信息
                     */
                    Map<String, SensorConfigDTO> sensorConfigMap = new HashMap();

                    baseParamDTO.getItems().stream().forEach(sensorConfigDTO -> {

                        sensorConfigMap.put(sensorConfigDTO.getSensorName(),sensorConfigDTO);

                    });

                    CacheCenterFactory.bridgeSensorConfigConnectionMap.put(bridgeCodeName,sensorConfigMap);

                }
            }

            System.err.println(CacheCenterFactory.bridgeSensorConfigConnectionMap);
        });

    }

    /**
     * 初始化配置文件中设备信息
     */
    public void initDeviceConfig(){

        //YX{3204211994:[32061914/FS#33250235/FX];2204211994:[]}&NH{345345:[32012344/FS#332363435/FX];22042567394:[]}

        //按桥名称拆分
        String[] birgeConfigs = this.deviceConfig.split("&");

        for (int i = 0; i < birgeConfigs.length; i++) {
            //YX{3204211994:[32061914/FS#33250235/FX];2204211994:[]}
            //拆分出该桥下的所有录入设备
            String[] deviceConfigs = birgeConfigs[i].split("\\{");
            //桥梁编码
            String bridgeCodeName = deviceConfigs[0];
            //录入设备信息
            String devConfig = deviceConfigs[1].substring(0, deviceConfigs[1].length() - 1);

            //3204211994:[32061914/FS#33250235/FX];2204211994:[]
            String[] dcs = devConfig.split(";");

            for (int k = 0; k < dcs.length; k++) {

                DeviceDTO deviceDTO = new DeviceDTO();
                //拆分出设备ID和设备下传感器信息
                String[] config = dcs[k].split(":");

                if(config.length <= 0){
                    return;
                }

                String deviceID = config[0];

                List<DeviceSensorDTO> dsDTO = new ArrayList<>();

                if(config[1].length() > 5){

                    String[] sensorConfig = config[1].substring(1,config[1].length()-1).split("#");

                    for (int j = 0; j < sensorConfig.length; j++) {
                        DeviceSensorDTO deviceSensorDTO = new DeviceSensorDTO();
                        String[] sidType = sensorConfig[j].split("/");

                        deviceSensorDTO.setSid(sidType[0]);
                        deviceSensorDTO.setSenType(sidType[1]);

                        dsDTO.add(deviceSensorDTO);
                    }

                    deviceDTO.init(null,deviceID,null,bridgeCodeName,dsDTO);
                }else{
                    deviceDTO.init(null,deviceID,null,bridgeCodeName,null);
                }

                CacheCenterFactory.deviceConfigMap.put(deviceID,deviceDTO);
            }
        System.err.println(CacheCenterFactory.deviceConfigMap);

        }


    }

}
